package com.turman.builibrary.tab.top;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;

import com.turman.blibrary.util.BDisplayUtil;
import com.turman.builibrary.tab.common.IBTabLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BTabTopLayout extends HorizontalScrollView implements IBTabLayout<BTabTopItem, BTabTopInfo<?>> {
    private List<OnTabSelectedListener<BTabTopInfo<?>>> tabSelectedListeners = new ArrayList<>();
    private BTabTopInfo<?> selectedInfo;
    private List<BTabTopInfo<?>> infoList;

    public BTabTopLayout(Context context) {
        super(context);
    }

    public BTabTopLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BTabTopLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public BTabTopItem findTab(@NonNull BTabTopInfo<?> data) {
        ViewGroup ll = getRootLayout(false);
        for (int i = 0; i < ll.getChildCount(); i++) {
            View child = ll.getChildAt(i);
            if (child instanceof BTabTopItem) {
                BTabTopItem item = (BTabTopItem) child;
                if (item.getInfo() == data) {
                    return item;
                }
            }
        }
        return null;
    }

    @Override
    public void addTabSelected(@NonNull OnTabSelectedListener<BTabTopInfo<?>> defaultInfo) {
        tabSelectedListeners.add(defaultInfo);
    }

    @Override
    public void defaultSelected(@NonNull BTabTopInfo<?> defaultInfo) {
        onSelected(defaultInfo);
    }

    @Override
    public void inflateInfo(@NonNull List<BTabTopInfo<?>> infoList) {
        setHorizontalScrollBarEnabled(false);
        if (infoList.isEmpty()) {
            return;
        }
        this.infoList = infoList;
        selectedInfo = null;

        Iterator<OnTabSelectedListener<BTabTopInfo<?>>> iterator = tabSelectedListeners.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() instanceof BTabTopItem) {
                iterator.remove();
            }
        }

        LinearLayout rootView = getRootLayout(true);
        for (int i = 0; i < infoList.size(); i++) {
            BTabTopInfo<?> info = infoList.get(i);
            BTabTopItem item = new BTabTopItem(getContext());
            item.setBTabInfo(info);
            tabSelectedListeners.add(item);
            rootView.addView(item);
            item.setOnClickListener(v -> onSelected(info));
        }
    }

    private void onSelected(@NonNull BTabTopInfo<?> nextInfo) {
        for (OnTabSelectedListener<BTabTopInfo<?>> listener : tabSelectedListeners) {
            listener.onTabSelectedChange(infoList.indexOf(nextInfo), selectedInfo, nextInfo);
        }
        this.selectedInfo = nextInfo;

        autoScroll(nextInfo);
    }

    /**
     * 保持点击项左侧或者右侧显示两个完整的tab（如果有的话）
     *
     * @author buobao
     * @since 2024/3/13 10:04
     */
    private void autoScroll(@NonNull BTabTopInfo<?> nextInfo) {
        BTabTopItem item = findTab(nextInfo);
        int[] location = new int[2];
        item.getLocationInWindow(location);
        int phoneWidth = BDisplayUtil.getDisplayWidthInPx(getContext());
        int direction = 0; //表示滚动方向 0-向左， 1-向右
        if (location[0] >= phoneWidth / 2) {
            direction = 1;
        }

        int index = infoList.indexOf(nextInfo);
        if (direction == 0 && index >= 1) {
            BTabTopItem needShowItem = findTab(index == 1 ? infoList.get(0) : infoList.get(index - 2));
            needShowItem.getLocationInWindow(location);
            if (location[0] < 0) {
                smoothScrollBy(location[0], 0);
            }
        }

        if (direction == 1 && index < infoList.size() - 1) {
            BTabTopItem needShowItem = findTab(index == infoList.size() - 2 ? infoList.get(index + 1) : infoList.get(index + 2));
            needShowItem.getLocationInWindow(location);
            int itemWidth = needShowItem.getWidth();
            if (phoneWidth - location[0] < itemWidth) {
                smoothScrollBy(itemWidth + location[0] - phoneWidth, 0);
            }
        }
    }

    private LinearLayout getRootLayout(boolean clear) {
        LinearLayout rootView = (LinearLayout) getChildAt(0);
        if (rootView == null) {
            rootView = new LinearLayout(getContext());
            rootView.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            addView(rootView, params);
        } else if (clear) {
            rootView.removeAllViews();
        }
        return rootView;
    }
}
















